package com.ruoyi.web.controller.cms.article;


import com.ruoyi.cms.article.domain.CmsArticle;
import com.ruoyi.cms.article.domain.vo.CmsArticleSearchVo;
import com.ruoyi.cms.article.service.ICmsArticleService;
import com.ruoyi.cms.fileInfo.service.ICmsFileInfoService;
import com.ruoyi.cms.tag.domain.CmsTag;
import com.ruoyi.cms.type.domain.CmsType;
import com.ruoyi.cms.type.service.ICmsTypeService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.SysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Set;

/**
 * 文章管理Controller
 */
@RestController("AdminCmsArticleController")
@RequestMapping("/admin/cms/article")
public class CmsArticleController extends BaseController {


    @Resource
    private ICmsArticleService cmsArticleService;

    @Resource
    private ICmsTypeService cmsTypeService;

    @Resource
    private SysPermissionService permissionService;


    @Resource
    private ICmsFileInfoService cmsFileInfoService;


    /**
     * 首页查询文章列表
     */
//    @GetMapping("/cms/cmsList")
//    public TableDataInfo cmsList(CmsArticle cmsArticle) {
//        startPage();
//        //状态为发布
//        cmsArticle.setStatus("1");
//        List<CmsArticle> list = cmsArticleService.selectCmsArticleList(cmsArticle);
//        return getDataTable(list);
//    }

    /**
     * 首页获取文章详细信息
     */
//    @GetMapping(value = {"/cms/detail/", "/cms/detail/{id}"})
//    public AjaxResult getInfoDetail(@PathVariable(value = "id", required = false) Long id) {
//        AjaxResult ajax = AjaxResult.success();
//        CmsType cmsType = new CmsType();
//        CmsTag cmsTag = new CmsTag();
//        ajax.put("types", cmsTypeService.selectCmsTypeList(cmsType));
////        ajax.put("tags", cmsTagService.selectCmsTagList(cmsTag));
//        if (StringUtils.isNotNull(id)) {
//            ajax.put(AjaxResult.DATA_TAG, cmsArticleService.selectCmsArticleById(id));
//        }
//        return ajax;
//    }

    /**
     * 首页按分类查询文章列表
     */
//    @GetMapping("/cms/cmsListByType/{id}")
//    public TableDataInfo cmsListByTypeId(@PathVariable(value = "id", required = false) Long id) {
//        startPage();
//        List<CmsArticle> list = cmsArticleService.selectCmsArticleListByTypeId(id);
//        return getDataTable(list);
//    }

    /**
     * 首页按标签查询文章列表
     */
//    @GetMapping("/cms/cmsListByTag/{id}")
//    public TableDataInfo cmsListByTagId(@PathVariable(value = "id", required = false) Long id) {
//        startPage();
//        List<CmsArticle> list = cmsArticleService.selectCmsArticleListByTagId(id);
//        return getDataTable(list);
//    }

    /**
     * 首页查询推荐文章列表
     */
//    @GetMapping("/cms/cmsListRecommend")
//    public TableDataInfo cmsListRecommend(CmsArticle cmsArticle) {
//        startPage();
//        //状态为发布
//        cmsArticle.setStatus("1");
//        List<CmsArticle> list = cmsArticleService.selectCmsArticleListRecommend(cmsArticle);
//        return getDataTable(list);
//    }

    /**
     * 首页增加阅读量
     */
//    @GetMapping("/cms/addArticleViews/{id}")
//    public AjaxResult addArticleViews(@PathVariable(value = "id", required = false) Long id) {
//        CmsArticle cmsArticle = cmsArticleService.selectCmsArticleById(id);
//        Long views = cmsArticle.getViews();
//        views += Long.parseLong("1");
//        cmsArticle.setViews(views);
//        cmsArticleService.updateCmsArticle(cmsArticle);
//        return AjaxResult.success(id);
//    }

    /**
     * 随笔页查询文章列表
     */
//    @GetMapping("/cms/cmsEssayList")
//    public TableDataInfo cmsEssayList(CmsArticle cmsArticle) {
//        startPage();
//        //状态为发布
//        cmsArticle.setStatus("1");
//        List<CmsArticle> list = cmsArticleService.selectCmsArticleList(cmsArticle);
//        return getDataTable(list);
//    }

    /**
     * 查询文章管理列表
     */
//    @PreAuthorize("@ss.hasPermi('cms:article:list')")
//    @GetMapping("/list")
//    public TableDataInfo list(CmsArticle cmsArticle) {
//        startPage();
//        List<CmsArticle> list = cmsArticleService.selectCmsArticleList(cmsArticle);
//        return getDataTable(list);
//    }
    @PreAuthorize("@ss.hasPermi('cms:article:list')")
    @GetMapping("/list")
    public TableDataInfo list(CmsArticleSearchVo vo) {
        startPage();
        List<CmsArticle> list = cmsArticleService.selectCmsArticleVoList(vo);
        return getDataTable(list);
    }


    /**
     * 导出文章管理列表
     */
    @PreAuthorize("@ss.hasPermi('cms:article:export')")
    @Log(title = "文章管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmsArticle cmsArticle) {
        List<CmsArticle> list = cmsArticleService.selectCmsArticleList(cmsArticle);
        ExcelUtil<CmsArticle> util = new ExcelUtil<>(CmsArticle.class);
        util.exportExcel(response, list, "文章管理数据");
    }

    /**
     * 获取文章管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('cms:article:query')")
    @GetMapping(value = {"/", "/{id}"})
    public AjaxResult getInfo(@PathVariable(value = "id", required = false) Long id) {
        AjaxResult ajax = AjaxResult.success();
        CmsType cmsType = new CmsType();
        ajax.put("types", cmsTypeService.selectCmsTypeList(cmsType));
        if (StringUtils.isNotNull(id)) {
            ajax.put(AjaxResult.DATA_TAG, cmsArticleService.selectCmsArticleById(id));
        }
        return ajax;
    }

    /**
     * 新增文章管理
     */
    @PreAuthorize("@ss.hasPermi('cms:article:add')")
    @Log(title = "文章管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmsArticle cmsArticle) {
        cmsArticle.setCreateBy(getUsername());
        Long articleId = cmsArticleService.insertCmsArticle(cmsArticle);
        if (articleId == null) {
            return AjaxResult.error();
        }
        return AjaxResult.success(articleId);
    }

    /**
     * 修改文章管理
     */
    @PreAuthorize("@ss.hasPermi('cms:article:edit')")
    @Log(title = "文章管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmsArticle cmsArticle) {
        cmsArticle.setUpdateBy(getUsername());
        //删除原首图
        CmsArticle oldArticle = cmsArticleService.selectCmsArticleById(cmsArticle.getId());
        if (cmsArticle.getArticlePic().isEmpty() || !cmsArticle.getArticlePic().equals(oldArticle.getArticlePic())) {
            if (!oldArticle.getArticlePic().isEmpty()) {
                String articlePic = oldArticle.getArticlePic();
                if (articlePic != null && !"".equals(articlePic)) {
                    int newFileNameSeparatorIndex = articlePic.lastIndexOf("/");
                    String FileName = articlePic.substring(newFileNameSeparatorIndex + 1).toLowerCase();
                    cmsFileInfoService.deleteCmsFileInfoByFileObjectName(FileName);
                }
            }
        }
        return toAjax(cmsArticleService.updateCmsArticle(cmsArticle));
    }

    /**
     * 删除文章管理
     */
    @PreAuthorize("@ss.hasPermi('cms:article:remove')")
    @Log(title = "文章管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        //删除原首图
        for (Long id : ids) {
            CmsArticle oldArticle = cmsArticleService.selectCmsArticleById(id);
            if (!oldArticle.getArticlePic().isEmpty()) {
                String articlePic = oldArticle.getArticlePic();
                if (articlePic != null && !"".equals(articlePic)) {
                    int newFileNameSeparatorIndex = articlePic.lastIndexOf("/");
                    String FileName = articlePic.substring(newFileNameSeparatorIndex + 1).toLowerCase();
                    cmsFileInfoService.deleteCmsFileInfoByFileObjectName(FileName);
                }
            }
        }
        return toAjax(cmsArticleService.deleteCmsArticleByIds(ids));
    }

    /**
     * 取消按钮-删除首图
     */
    @PreAuthorize("@ss.hasPermi('cms:article:edit')")
    @PostMapping("/cancel")
    public AjaxResult cancel(@RequestBody CmsArticle cmsArticle) {
        String articlePic = cmsArticle.getArticlePic();
        if (articlePic != null && !"".equals(articlePic)) {
            Long articleId = cmsArticle.getId();
            if (articleId == null) {
                int newFileNameSeparatorIndex = articlePic.lastIndexOf("/");
                String FileName = articlePic.substring(newFileNameSeparatorIndex + 1).toLowerCase();
                cmsFileInfoService.deleteCmsFileInfoByFileObjectName(FileName);
            } else {
                String Pic = cmsArticleService.selectCmsArticleById(articleId).getArticlePic();
                if (!articlePic.equals(Pic)) {
                    int newFileNameSeparatorIndex = articlePic.lastIndexOf("/");
                    String FileName = articlePic.substring(newFileNameSeparatorIndex + 1).toLowerCase();
                    cmsFileInfoService.deleteCmsFileInfoByFileObjectName(FileName);
                }
            }
        }
        return toAjax(1);
    }
}
